import axios from 'axios'
import store from '@/store'
import router from '../router';
import { Message } from 'element-ui';
import NProgress from 'nprogress';

axios.interceptors.request.use(
	(request) => {
		NProgress.start();
		return request;
	},
	(err) => {
		return Promise.reject(err);
	}
);

axios.interceptors.response.use(
	(success) => {
		NProgress.done();
		if (success.status && success.status == 200 && success.data.status == 500) {
			//把后台的出错消息写出来
			Message.error({ message: success.data.msg });
			return;
		}
		if (success.data.msg) {
			//把操作成功的信息也弹出来
			Message.success({ message: success.data.msg });
		}
		return success.data;
	},
	(error) => {
		//失败的处理
		if (error.response.status == 504 || error.response.status == 404) {
			Message.error({ message: '服务器被吃了哦！' });
		} else if (error.response.status == 403) {
			Message.error({ message: '权限不足，请联系管理员' });
		} else if (error.response.status == 401) {
			Message.error({ message: '尚未登录' });
			router.replace('/login');
		} else {
			//服务器返回的错误信息
			if (error.response.data.msg) {
				Message.error({ message: error.response.data.msg });
			} else {
				Message.error({ message: '未知错误' });
			}
		}
		return;
	}
);


export default axios;
